package com.wehealth;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.umeng.analytics.MobclickAgent;
import com.wehealth.adapter.Adapter_QuestionList;
import com.wehealth.adapter.Adapter_QuestionReply;
import com.wehealth.adapter.Adapter_message;
import com.wehealth.adapter.QuestionReplyDate;
import com.wehealth.dm.DM_Messages;
import com.wehealth.dm.QuestionData;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

@SuppressLint("ValidFragment")
public class Question_reply extends Fragment {
	
	private static  String JSONResult;
	private List<QuestionReplyDate> listData;
	private MainActivity context;
    private  String QID;
    private ListView listView;
	private static final int NET_ERROR = -100;
	private static final int NOT_RECORD = -101;
	private static final int NOUSER_ERROR =-102;
	private ProgressBar mProgress;
	private QuestionData mData;
	private AlertDialog dialog;

	public  Question_reply()
	{
		Log.i("init:", "Message"); 

	}
	
	public  void setQID(String qid)
	{
		QID = qid;
	}
	
	public  void setData(QuestionData data)
	{
		mData = data;
	}
	
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return  inflater.inflate(R.layout.question_reply, null);
	}
	
	
	
	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);
		
		//SIMMON_ADD
		//读取接口数据
		context = (MainActivity)getActivity();
		MobclickAgent.openActivityDurationTrack(false);
		mProgress =(ProgressBar)context.findViewById(R.id.question_reply_progress);
		mProgress.setVisibility(View.VISIBLE);
		listView = (ListView)context.findViewById(R.id.questionreplylist);
		ConnService();
		
		TextView mTitle = (TextView) context.findViewById(R.id.header).findViewById(R.id.header_title);
		String title =context.getString(R.string.question_reply_title);
		mTitle.setText(title);
		
		//返回主页按钮-------------------------------------------------------//
		 Button bBack = (Button) context.findViewById(R.id.header_bBack);
			
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
					
				    context.switchContentHome();
				}
			});
			
		//------------------------------------------------------------------//
		 
		 TextView timeTv =(TextView)context.findViewById(R.id.question_time_tv);
		 timeTv.setText(mData.gettime());
		 
		 TextView keshiTv =(TextView)context.findViewById(R.id.question_depart_tv);
		 keshiTv.setText(mData.getDepartName());
		 
		 TextView descripTv =(TextView)context.findViewById(R.id.question_descrip_tv);
		 descripTv.setText(mData.getDesciption());
		 
		 
		 Button reply_bt =(Button)context.findViewById(R.id.question_add_new);
		 reply_bt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Question_reply_add newFragment = new Question_reply_add();
				newFragment.setQID(mData.getQID());
				context.switchContent(newFragment);	
			}
		});
		 
		  
	}


		private void  ConnService(){
			
			//读取接口数据
			new Thread(){
				@Override
				public void run(){
				//你要执行的方法
					try {
						InitThisView();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				//执行完毕后给handler发送一个空消息
				handler.sendEmptyMessage(0);
				}
				}.start();
		}
		
		private void  InitThisView() throws IOException
		{
			 String urlAPI = "http://www.552120.com:8092/Question_GetReplyList.aspx";
			 HttpPost httpRequest= new HttpPost(urlAPI);
			 List <NameValuePair> params = new ArrayList <NameValuePair>(); 
			 String qid = mData.getQID();
			 params.add(new BasicNameValuePair("QID",qid));
			 Log.d("SIMMON","   qid= "+qid);
			 //params.add(new BasicNameValuePair("QID","45b6eb99-9e40-4d7b-bd89-38a803b5a59e"));
			 try
			 {
				 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
				 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);		 
				 if(httpResponse.getStatusLine().getStatusCode() == 200)
				 {	
					 JSONResult = EntityUtils.toString(httpResponse.getEntity()); 
				 }		 
			 }
			 catch(Exception e)
			 {		
				 Log.e("error:",  e.toString());
			 }

		}
		
		
		
		//定义Handler对象
		private Handler handler =new Handler(){
			@Override
			public void handleMessage(Message msg){
			super.handleMessage(msg);
			//处理UI
			 Log.d("SIMMON"," handleMessage  ");
			if(JSONResult ==null){
				openDialog(NET_ERROR);
			}else{
				BindList(JSONResult);
				JSONResult =null;
			}
			}
		};
		

		
		//将JSON数据绑定到LISTVIEW
		private void BindList(String strJSON)
		{
			    try
			    {
					 Log.d("SIMMON"," BindList222 strJSON= "+strJSON);
				    JSONObject jsonObject = new JSONObject(strJSON); 
				    Log.d("SIMMON"," BindList333  ");
				    JSONArray  aNews =  new JSONArray( jsonObject.getString("result") );  
				    listData = new ArrayList<QuestionReplyDate>();
					Log.d("SIMMON","   BindList    ="+aNews.length());
				    if(aNews.length() ==0){
				    	openDialog(NOT_RECORD);
				    }
				    for(int i=0; i<aNews.length(); i++)
				    {
				    	QuestionReplyDate  reply = new QuestionReplyDate();
				    	reply.setTime(aNews.getJSONObject(i).getString("time"));
				    	reply.setReply(aNews.getJSONObject(i).getString("reply"));
				    	reply.setisDr(aNews.getJSONObject(i).getString("isDr"));
				    	reply.setOwnerID(aNews.getJSONObject(i).getString("ownerID"));
				    	listData.add(reply);
				    }

				    updateViewData(listData);
			    }
			    catch(JSONException ex)
			    {
			    		Log.e("JSON Error: ", ex.toString()); 
			    }
		}
		
		private  void updateViewData(List<QuestionReplyDate> datas ){		
			 Log.d("SIMMON"," BindList333  ");
			 mProgress.setVisibility(View.GONE);
			Adapter_QuestionReply adapter = new Adapter_QuestionReply(context, datas);
	        listView.setAdapter(adapter);
		}
	    
		  private void openDialog(final int result){
			   mProgress.setVisibility(View.GONE);
		        String login_result = context.getString(R.string.regist_fail);
		    
		        switch (result) {
		        case NET_ERROR:
		            login_result = getString(R.string.net_connet_fail);
		            break;
		        case NOT_RECORD:
		            login_result = getString(R.string.question_no_record);
		            break;
		        case NOUSER_ERROR:
		            login_result = getString(R.string.cons_submit_nouser);
		            break;
		      }

	              final AlertDialog.Builder builder = new AlertDialog.Builder(context); 
	                 View view = LayoutInflater.from(context).inflate(R.layout.dialog_self_viewbt,null);
	                 TextView textview = (TextView)view.findViewById(R.id.dialog_self_tx);
	                 textview.setText(login_result);
	                 Button okBt =(Button)view.findViewById(R.id.dialog_self_bt);
	                 String okBtBtStr ="确定";
	                 okBt.setText(okBtBtStr);
	                 okBt.setOnClickListener(new OnClickListener() {
	                    
	                    @Override
	                    public void onClick(View arg0) {
	                        // TODO Auto-generated method stub
                            Home vHome = new Home();
                            context.switchContent(vHome); 
	                        dialog.cancel();
	                    }
	                });
	                 builder.setView(view);
	                 dialog=  builder.create();
	                 dialog.show();
		         
		         
		     }

}
